import traceback

from fastapi import FastAPI, Request
import uvicorn
from starlette.responses import JSONResponse

from model.model import Request_data, Item_data
from service import similarity_service

app = FastAPI()


async def all_exception_handler(request: Request, call_next):
    # print(f'<================== 全局异常 ==============>\n{traceback.format_exc()}')
    try:
        return await call_next(request)
    except Exception as e:
        print(f"全局异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}")
        with open('log/gunicorn_error.log', "a") as f:
            traceback.print_exc(file=f)
        return JSONResponse(status_code=500, content={"code": 500, "msg": '出错了， 请重试', "result": None}, )


app.middleware('http')(all_exception_handler)


@app.post('/docDiff')
async def fileComparison(request_data: Request_data):
    return similarity_service.similarity_cont(request_data)


@app.post('/word2Vec')
async def word2Vec(item_data: Item_data):
    return await similarity_service.word2Vec(item_data)


# if __name__ == '__main__':
#     uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True)